package com.app.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.app.biz.domain.OperationFocusProduct;
import com.app.biz.domain.OperationMetric;
import com.app.biz.excel.entity.BizIndustrialSectorMetricsExcelEntity;
import com.app.biz.mapper.BizIndustrialSectorMetricsFormalMapper;
import com.app.biz.service.IOperationService;
import com.app.common.annotation.Excel;
import com.app.common.core.domain.AjaxResult;
import com.app.common.core.domain.entity.SysDictData;
import com.app.common.utils.DateUtils;
import com.app.common.utils.DictUtils;
import com.app.common.utils.uuid.IdUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.biz.mapper.BizIndustrialSectorMetricsMapper;
import com.app.biz.domain.BizIndustrialSectorMetrics;
import com.app.biz.service.IBizIndustrialSectorMetricsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 分行业企业主要经济指标临时Service业务层处理
 *
 * @author SangGuangCan
 * @date 2024-01-02
 */
@Service
public class BizIndustrialSectorMetricsServiceImpl implements IBizIndustrialSectorMetricsService
{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    private final BizIndustrialSectorMetricsMapper bizIndustrialSectorMetricsMapper;

    private final BizIndustrialSectorMetricsFormalMapper bizIndustrialSectorMetricsFormalMapper;

    @Autowired
    private IOperationService operationService;

    @Autowired
    public BizIndustrialSectorMetricsServiceImpl(BizIndustrialSectorMetricsMapper bizIndustrialSectorMetricsMapper,
                                                 BizIndustrialSectorMetricsFormalMapper bizIndustrialSectorMetricsFormalMapper){
        this.bizIndustrialSectorMetricsMapper = bizIndustrialSectorMetricsMapper;
        this.bizIndustrialSectorMetricsFormalMapper = bizIndustrialSectorMetricsFormalMapper;

    }

    /**
     * 查询分行业企业主要经济指标临时
     *
     * @param baseId 分行业企业主要经济指标临时主键
     * @return 分行业企业主要经济指标临时
     */
    @Override
    public BizIndustrialSectorMetrics selectBizIndustrialSectorMetricsByBaseId(String baseId)
    {
        return bizIndustrialSectorMetricsMapper.selectBizIndustrialSectorMetricsByBaseId(baseId);
    }

    /**
     * 查询分行业企业主要经济指标临时列表
     *
     * @param bizIndustrialSectorMetrics 分行业企业主要经济指标临时
     * @return 分行业企业主要经济指标临时
     */
    @Override
    public List<BizIndustrialSectorMetrics> selectBizIndustrialSectorMetricsList(BizIndustrialSectorMetrics bizIndustrialSectorMetrics)
    {
        return bizIndustrialSectorMetricsMapper.selectBizIndustrialSectorMetricsList(bizIndustrialSectorMetrics);
    }

    /**
     * 新增分行业企业主要经济指标临时
     *
     * @param bizIndustrialSectorMetrics 分行业企业主要经济指标临时
     * @return 结果
     */
    @Override
    public int insertBizIndustrialSectorMetrics(BizIndustrialSectorMetrics bizIndustrialSectorMetrics)
    {
        bizIndustrialSectorMetrics.setBaseId(IdUtils.simpleUUID());
        bizIndustrialSectorMetrics.setBaseCreateTime(DateUtils.getNowDate());
        return bizIndustrialSectorMetricsMapper.insertBizIndustrialSectorMetrics(bizIndustrialSectorMetrics);
    }

    /**
     * 修改分行业企业主要经济指标临时
     *
     * @param bizIndustrialSectorMetrics 分行业企业主要经济指标临时
     * @return 结果
     */
    @Override
    public int updateBizIndustrialSectorMetrics(BizIndustrialSectorMetrics bizIndustrialSectorMetrics)
    {
        return bizIndustrialSectorMetricsMapper.updateBizIndustrialSectorMetrics(bizIndustrialSectorMetrics);
    }

    /**
     * 批量删除分行业企业主要经济指标临时
     *
     * @param baseIds 需要删除的分行业企业主要经济指标临时主键
     * @return 结果
     */
    @Override
    public int deleteBizIndustrialSectorMetricsByBaseIds(String[] baseIds)
    {
        return bizIndustrialSectorMetricsMapper.deleteBizIndustrialSectorMetricsByBaseIds(baseIds);
    }

    /**
     * 删除分行业企业主要经济指标临时信息
     *
     * @param baseId 分行业企业主要经济指标临时主键
     * @return 结果
     */
    @Override
    public int deleteBizIndustrialSectorMetricsByBaseId(String baseId)
    {
        return bizIndustrialSectorMetricsMapper.deleteBizIndustrialSectorMetricsByBaseId(baseId);
    }

    /**
     * <p>
     * 将临时表中的数据转移到正式表
     * </p>
     *
     * @return 返回false或ture
     */
    @Override
    public boolean transferDataInOneClick(){
        try{
            /* 查询数据库中最新的一条日期 */
//            String latestDateStr = bizIndustrialSectorMetricsMapper.getLatestDateData();
//            BizIndustrialSectorMetrics params = new BizIndustrialSectorMetrics();
//            params.setYearMonth(DateUtils.parseDate(latestDateStr,"yyyy-MM-dd"));

            List<BizIndustrialSectorMetrics> result = bizIndustrialSectorMetricsMapper.selectBizIndustrialSectorMetricsAllData();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
            int count = 0;
            List<BizIndustrialSectorMetrics> list = new ArrayList<>();
            for(BizIndustrialSectorMetrics item : result){
                item.setBaseCreateTime(DateUtils.getNowDate());
                list.add(item);
                count++;
                if(count >= 100){
                      bizIndustrialSectorMetricsFormalMapper.batchInsertBizIndustrialSectorMetricsFormal(list);

                    List<OperationMetric> olist=list.stream().map(items->{
                        OperationMetric operationMetric=new OperationMetric();
                        operationMetric.setBaseId(items.getBaseId());
                        operationMetric.setMetricName(items.getMetricName());
                        operationMetric.setCompanyCount(items.getCompanyCountEndOfMonth());
                        operationMetric.setMonthToRevenue(items.getMonthToDateRevenue());
                        operationMetric.setIncomeVariance(items.getIncomeVariance());
                        operationMetric.setMtdProfit(items.getMtdProfit());
                        operationMetric.setTotalProfitDelta(items.getTotalProfitDelta());
                        operationMetric.setYearMonth(simpleDateFormat.format(items.getYearMonth()));
                        operationMetric.setBaseCreateTime(new Date());
                        operationMetric.setRemarks(items.getRemark());
                        return  operationMetric;
                    }).collect(Collectors.toList());
                    operationService.batchInsertOperationMetric(olist);
                    list.clear();
                    olist.clear();
                }
            }

            if(!list.isEmpty()){
                bizIndustrialSectorMetricsFormalMapper.batchInsertBizIndustrialSectorMetricsFormal(list);
                List<OperationMetric> olist=list.stream().map(items->{
                    OperationMetric operationMetric=new OperationMetric();
                    operationMetric.setBaseId(items.getBaseId());
                    operationMetric.setMetricName(items.getMetricName());
                    operationMetric.setCompanyCount(items.getCompanyCountEndOfMonth());
                    operationMetric.setMonthToRevenue(items.getMonthToDateRevenue());
                    operationMetric.setIncomeVariance(items.getIncomeVariance());
                    operationMetric.setMtdProfit(items.getMtdProfit());
                    operationMetric.setTotalProfitDelta(items.getTotalProfitDelta());
                    operationMetric.setYearMonth(simpleDateFormat.format(items.getYearMonth()));
                    operationMetric.setBaseCreateTime(new Date());
                    operationMetric.setRemarks(items.getRemark());
                    return  operationMetric;
                }).collect(Collectors.toList());
                operationService.batchInsertOperationMetric(olist);
                list.clear();
                olist.clear();

            }
            return true;
        }catch (Exception e){
            logger.error("未知错误:{}",e.getMessage());
            return false;
        }
    }

    /**
     *
     */
    @Override
    public void clearAllTableData() {
        bizIndustrialSectorMetricsMapper.clearAllTableData();
    }

    /**
     * @return
     */
    @Override
    public List<String> getUniqueDatesFromDatabase() {
        List<String> uniqueDatesFromDatabase = bizIndustrialSectorMetricsMapper.getUniqueDatesFromDatabase();
        if(!uniqueDatesFromDatabase.isEmpty()){
            //Mysql中去重关键字和排序不能对同一字段同时使用，这里通过代码来去重
            return uniqueDatesFromDatabase.stream().distinct().collect(Collectors.toList());
        }
        return uniqueDatesFromDatabase;
    }

    /**
     * <p>
     * 导入分行业企业主要经济指标数据
     * </p>
     *
     * @param absoluteExcelPath
     * @param yearMonth
     * @return 导入是否成功
     */
    @Override
    public AjaxResult importExcel(String absoluteExcelPath, String yearMonth) {
        List<BizIndustrialSectorMetricsExcelEntity> excelDataArgs = EasyExcel.read(absoluteExcelPath).head(BizIndustrialSectorMetricsExcelEntity.class).headRowNumber(5).sheet("分行业").doReadSync();
        try{
            if(excelDataArgs.isEmpty()){
                logger.warn("分行业企业主要经济指标数据");
                return AjaxResult.warn("分行业企业主要经济指标数据停止导入,原因:未加载到Excel中的数据");
            }
            List<BizIndustrialSectorMetrics> list = new ArrayList<>();
            List<SysDictData> industryIndicatorsDict = DictUtils.getDictCache("industry_indicators");
            if(industryIndicatorsDict == null || industryIndicatorsDict.isEmpty()){
                logger.warn("分行业企业主要经济指标数据停止导入");
                return AjaxResult.warn("分行业企业主要经济指标数据停止导入,原因:未找到行业指标数据");
            }
            Map<String, String> industryIndicatorsDictMap = industryIndicatorsDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
            for(BizIndustrialSectorMetricsExcelEntity item : excelDataArgs){
                String noSpaceStr = StringUtils.trimAllWhitespace(item.getMetricName());
                if(!industryIndicatorsDictMap.containsKey(noSpaceStr)){
                    continue;
                }
                BizIndustrialSectorMetrics bizIndustrialSectorMetrics = new BizIndustrialSectorMetrics();
                BeanUtil.copyProperties(item,bizIndustrialSectorMetrics);
                bizIndustrialSectorMetrics.setMetricName(industryIndicatorsDictMap.get(noSpaceStr));
                bizIndustrialSectorMetrics.setBaseCreateTime(DateUtils.getNowDate());
                bizIndustrialSectorMetrics.setBaseId(IdUtils.simpleUUID());
                bizIndustrialSectorMetrics.setYearMonth(DateUtil.parse(yearMonth,"yyyy-MM"));
                list.add(bizIndustrialSectorMetrics);
            }
            if(list.isEmpty()){
                logger.warn("分行业企业主要经济指标数据数组为空");
            }else{
                bizIndustrialSectorMetricsMapper.batchInsertBizIndustrialSectorMetrics(list);
            }
            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error("导入失败");
        }
    }

    /**
     * @return
     */
    @Override
    public List<BizIndustrialSectorMetrics> selectBizIndustrialSectorMetricsListNoParams() {
        return bizIndustrialSectorMetricsMapper.selectBizIndustrialSectorMetricsListNoParams();
    }
}
